package com.ruoyi.web.controller.gift;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.gift.domain.MaintenanceRecord;
import com.ruoyi.gift.domain.dto.MaintenanceRecordQuery;
import com.ruoyi.gift.domain.page.PageResult;
import com.ruoyi.gift.service.MaintenanceRecordService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 维修记录
 */
@Api("维修记录管理")
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/maintenance")
public class MaintenanceRecordController extends BaseController {

    private final MaintenanceRecordService maintenanceRecordService;

    /**
     * 新增维修记录
     */
    @PreAuthorize("@ss.hasRole('record')")
    @PostMapping("/add")
    public AjaxResult addMaintenanceRecord(@Valid @RequestBody MaintenanceRecord maintenanceRecord) {
        try {
            maintenanceRecordService.addMaintenanceRecord(maintenanceRecord);
            return success("维修记录新增成功");
        } catch (Exception e) {
            log.error("新增维修记录失败：{}", e.getMessage());
            return error(e.getMessage());
        }
    }

    /**
     * 更新维修记录
     */
    @PreAuthorize("@ss.hasRole('record')")
    @PutMapping("/update")
    public AjaxResult updateMaintenanceRecord(@Valid @RequestBody MaintenanceRecord maintenanceRecord) {
        try {
            maintenanceRecordService.updateMaintenanceRecord(maintenanceRecord);
            return success("维修记录更新成功");
        } catch (Exception e) {
            log.error("更新维修记录失败：{}", e.getMessage());
            return error(e.getMessage());
        }
    }

    /**
     * 根据ID查询维修记录
     */
    @PreAuthorize("@ss.hasRole('record')")
    @GetMapping("/{id}")
    public AjaxResult getMaintenanceRecordById(@PathVariable @NotNull Long id) {
        try {
            MaintenanceRecord record = maintenanceRecordService.getById(id);
            if (record == null) {
                error("维修记录不存在");
            }
            return success(record);
        } catch (Exception e) {
            log.error("查询维修记录失败：{}", e.getMessage());
            return error(e.getMessage());
        }
    }

    /**
     * 查询维修记录列表（分页）
     */
    @GetMapping("/list")
    public TableDataInfo getMaintenanceRecordList(MaintenanceRecordQuery query) {
        startPage();
        List<MaintenanceRecord> result = maintenanceRecordService.getMaintenanceRecordList(query);
        return getDataTable(result);
    }

    /**
     * 删除维修记录
     */
    @PreAuthorize("@ss.hasRole('record')")
    @DeleteMapping("/{id}")
    public AjaxResult deleteMaintenanceRecord(@PathVariable @NotNull Long id) {
        try {
            maintenanceRecordService.deleteMaintenanceRecord(id);
            return success("维修记录删除成功");
        } catch (Exception e) {
            log.error("删除维修记录失败：{}", e.getMessage());
            return error(e.getMessage());
        }
    }

    /**
     * 根据路牌ID查询维修记录
     */
    @GetMapping("/by-sign/{signId}")
    public AjaxResult getMaintenanceBySignId(@PathVariable @NotNull Long signId) {
        try {
            List<MaintenanceRecord> records = maintenanceRecordService.getBySignId(signId);
            return success(records);
        } catch (Exception e) {
            log.error("根据路牌ID查询维修记录失败：{}", e.getMessage());
            return error(e.getMessage());
        }
    }

    /**
     * 根据路牌编号查询维修记录
     */
    @GetMapping("/by-sign-code/{signCode}")
    public AjaxResult getMaintenanceBySignCode(@PathVariable @NotNull String signCode) {
        try {
            List<MaintenanceRecord> records = maintenanceRecordService.getBySignCode(signCode);
            return success(records);
        } catch (Exception e) {
            log.error("根据路牌编号查询维修记录失败：{}", e.getMessage());
            return error(e.getMessage());
        }
    }

    /**
     * 获取路牌维修统计
     */
    @GetMapping("/stats/{signId}")
    public AjaxResult getMaintenanceStats(@PathVariable @NotNull Long signId) {
        try {
            List<MaintenanceRecord> records = maintenanceRecordService.getBySignId(signId);
            int totalCount = records.size();
            double totalCost = records.stream()
                    .mapToDouble(record -> record.getTotalFee() != null ? record.getTotalFee().doubleValue() : 0.0)
                    .sum();

            java.util.Map<String, Object> stats = new java.util.HashMap<>();
            stats.put("totalCount", totalCount);
            stats.put("totalCost", totalCost);
            stats.put("lastMaintenanceDate",
                    records.isEmpty() ? null : records.get(0).getMaintenanceDate());

            return success(stats);
        } catch (Exception e) {
            log.error("获取维修统计失败：{}", e.getMessage());
            return error(e.getMessage());
        }
    }
}